/**
 * Created by tomi on 1/29/15.
 */
var mongoose = require('mongoose');
var ResponseCode = require('../util/ResponseNumber');
var UUID = require('node-uuid');

var UserSchema = mongoose.Schema({
    username: String,
    password: String,
    nickname: String,
    sports: [{type: mongoose.Schema.Types.ObjectId, ref: 'Sport'}],
    token: String
});


UserSchema.statics.register = function (username, password, cb) {
    console.log("register with username: " + username + " password: " + password);

    //check if the username has been taken or not.
    User.findOne({'username': username}, function (err, user) {
        // check the user is exist or not.
        if (user && user.length !== 0) {
            cb(ResponseCode.common_error);
            return;
        }

        // new user base on the user info.
        var newUser = new User({
            username: username,
            password: password
        });

        // save into db.
        newUser.save(function (err) {
            console.log(err);
            cb(err);
        });
    })

};


UserSchema.statics.findByToken = function (token, cb) {

    User.findOne({token: token}, function (err, user) {

        if (err) {
            cb(ResponseCode.common_error);
            return;
        }

        if (user === null || user === undefined) {
            cb(ResponseCode.common_error);
            return;
        }

        cb(null, user);
    });
};

UserSchema.statics.login = function (username, password, cb) {

    User.findOne({username: username, password: password}, function (err, user) {
        if (err) {
            cb(ResponseCode.common_error);
            return;
        }

        if (user === null || user === undefined) {
            cb(ResponseCode.common_error);
            return;
        }

        user.token = UUID.v4();
        user.save(user, function (err, user) {
            cb(null, user);
        });
        
    });


};


var User = mongoose.model('User', UserSchema);

module.exports = User;